#!/bin/bash

# 性能分析脚本 - 从训练日志中提取FPS等性能指标
# 使用方法: ./performance_analysis.sh <log_file_path>

# 检查参数
if [ $# -eq 0 ]; then
    echo "错误: 请提供日志文件路径"
    echo "使用方法: $0 <log_file_path>"
    echo "示例: $0 /path/to/train.log"
    exit 1
fi

log_file=$1

# 检查日志文件是否存在
if [ ! -f "$log_file" ]; then
    echo "错误: 日志文件 '$log_file' 不存在"
    exit 1
fi

echo "==================== 性能分析报告 ===================="
echo "日志文件: $log_file"
echo "分析时间: $(date)"
echo "======================================================"

# 1. 提取每个epoch的平均时间
echo "正在分析训练时间..."
avg_time=$(grep -a 'mmdet - INFO - Epoch ' "$log_file" | \
           awk -F "time: " '{print $2}' | \
           awk -F ", " '{print $1}' | \
           awk '{a+=$1} END {if (NR != 0) printf("%.3f",a/NR)}')

if [ -z "$avg_time" ]; then
    echo "警告: 未找到标准的mmdet训练时间信息"
    # 尝试其他可能的日志格式
    avg_time=$(grep -a "time:" "$log_file" | \
               awk -F "time:" '{print $2}' | \
               awk '{print $1}' | \
               awk '{a+=$1} END {if (NR != 0) printf("%.3f",a/NR)}')
fi

Iteration_time=$avg_time

# 2. 提取batch size信息（如果有的话）
batch_size=$(grep -a "batch_size" "$log_file" | head -1 | grep -o "batch_size[: ]*[0-9]*" | grep -o "[0-9]*")
if [ -z "$batch_size" ]; then
    # 尝试从配置信息中提取
    batch_size=$(grep -a "samples_per_gpu" "$log_file" | head -1 | grep -o "[0-9]*")
fi

# 3. 计算性能指标
echo ""
echo "================== 性能指标 =================="
echo "平均每轮训练时间: ${avg_time:-N/A} 秒"

if [ ! -z "$avg_time" ] && [ "$avg_time" != "0.000" ]; then
    # 计算每秒处理的iterations
    iterations_per_second=$(echo "scale=3; 1 / $avg_time" | bc -l 2>/dev/null)
    echo "每秒处理迭代数: ${iterations_per_second:-N/A} iter/s"
    
    # 如果有batch_size，计算FPS
    if [ ! -z "$batch_size" ] && [ "$batch_size" != "0" ]; then
        fps=$(echo "scale=2; $iterations_per_second * $batch_size" | bc -l 2>/dev/null)
        echo "批处理大小: $batch_size"
        echo "FPS (帧/秒): ${fps:-N/A}"
    else
        echo "批处理大小: 未检测到"
        echo "FPS: 需要批处理大小信息才能计算"
    fi
else
    echo "错误: 无法提取有效的训练时间信息"
fi

# 4. 统计训练轮数
total_epochs=$(grep -a 'mmdet - INFO - Epoch ' "$log_file" | wc -l)
if [ "$total_epochs" -eq 0 ]; then
    total_epochs=$(grep -c "Epoch" "$log_file")
fi
echo "总训练轮数: $total_epochs"

# 5. 提取GPU利用率信息（如果有的话）
echo ""
echo "================== 其他信息 =================="
gpu_info=$(grep -a "GPU" "$log_file" | head -3)
if [ ! -z "$gpu_info" ]; then
    echo "GPU信息:"
    echo "$gpu_info"
else
    echo "GPU信息: 未找到"
fi

# 6. 提取内存使用信息
memory_info=$(grep -a -i "memory\|mem" "$log_file" | head -3)
if [ ! -z "$memory_info" ]; then
    echo ""
    echo "内存使用信息:"
    echo "$memory_info"
fi

# 7. 查找错误信息
error_count=$(grep -c -i "error\|failed\|exception" "$log_file")
if [ "$error_count" -gt 0 ]; then
    echo ""
    echo "警告: 发现 $error_count 个错误信息"
    echo "最近的错误:"
    grep -i "error\|failed\|exception" "$log_file" | tail -3
fi

echo ""
echo "==================== 分析完成 ===================="

# 8. 生成性能摘要文件
summary_file="${log_file%.*}_performance_summary.txt"
cat > "$summary_file" << EOF
性能摘要报告
生成时间: $(date)
日志文件: $log_file
平均训练时间: ${avg_time:-N/A} 秒
每秒迭代数: ${iterations_per_second:-N/A}
批处理大小: ${batch_size:-N/A}
FPS: ${fps:-N/A}
总训练轮数: $total_epochs
EOF

echo "性能摘要已保存至: $summary_file"